﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Web.Configuration;
using WeatherAggregator;

namespace WebUi.Web
{
	[ServiceContract(Namespace = @"http://alexus.dyndns.info/dev/weatheraggregator/dataforclients")]
	[SilverlightFaultBehavior]
	[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
	public class DataForClients
	{

		[OperationContract]
		public List<WeatherDto> LastEntries(String cityFilter = null)
		{
			const int count = 200;

			using (var c = GetDataContextHelper())
			{
				var q1 = String.IsNullOrWhiteSpace(cityFilter)
				         	? c.WeatherDataEntries
				         	: c.WeatherDataEntries.Where(_ => _.CityName == cityFilter);

				var entries = q1
					.OrderByDescending(_ => _.TimeUtc)
					.Take(count)
					.Select(entry => new WeatherDto(entry))
					.ToList();
				return entries;
			}
		}

		[OperationContract]
		public List<String> GetCities()
		{
			using (var c = GetDataContextHelper())
			{
				var cities = c.WeatherDataEntries.Select(_ => _.CityName).Distinct();
				return cities.ToList();
			}
		}


		#region Helpers

		static String _conString;

		static DataContext GetDataContextHelper()
		{
			if (String.IsNullOrWhiteSpace(_conString))
			{
				var conStringSection =
					WebConfigurationManager.ConnectionStrings
						.Cast<ConnectionStringSettings>()
						.Where(_ => _.Name != "LocalSqlServer")
						.FirstOrDefault();
				if (conStringSection == null ||
				    String.IsNullOrWhiteSpace(conStringSection.ConnectionString))
					throw new Exception("Ошибка конфигурации сервера: не задана строка подключения к БД");
				_conString = conStringSection.ConnectionString;
			}

			var c = Helper.GetDataContext(_conString);
			return c;
		}

		#endregion
	}

}